package com.bit.lotterySystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private final static ObjectMapper objectaMapper;
    static {
        objectaMapper = new ObjectMapper();
    }
    private static ObjectMapper getObjectaMapper() {
        return objectaMapper;
    }
    private static <T> T tryParse(Callable<T> parser) {
       return tryParse(parser, JacksonException.class);
    }
    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return (T)parser.call();
        } catch (Exception ex) {
            if (check.isAssignableFrom(ex.getClass())) {
                throw new JsonParseException(ex);
            }
            throw new IllegalStateException(ex);
        }
    }

    /**
     * 序列化
     * @param object
     * @return
     */
    public static String writeValueAsString(Object object) {
        return tryParse(()-> {
           return  JacksonUtil.getObjectaMapper().writeValueAsString(object);
         }
        );
    }

    /**
     * 反序列化
     * @param value
     * @param valueType
     * @return
     * @param <T>
     */
    public static <T> T readValue(String value, Class<T> valueType) {
        return tryParse(()->{
            return getObjectaMapper().readValue(value, valueType);
        });
    }
    public static <T> List<T> readListValue(String value, Class<T> valueType) {
        JavaType javaType = JacksonUtil.getObjectaMapper().getTypeFactory().constructParametricType(List.class, valueType);
        return tryParse(()->{
            return getObjectaMapper().readValue(value, javaType);
        });
    }
}
